//
//  Singleton.m
//  TicketingSystem
//
//  Created by Conner Wu on 15/7/20.
//  Copyright (c) 2015年 Beyondsoft. All rights reserved.
//

#import "Singleton.h"
#import "MBProgressHUD.h"
#import "AppDelegate.h"


//#import "AWLocationManager.h"
@interface Singleton ()
{
    MBProgressHUD *_loadingView;
    NSUInteger _loadingCount;
}
@end

@implementation Singleton

+ (instancetype)shareInstance
{
    static id instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[[self class] alloc] init];
    });
	return instance;
}

- (id)init{
    self = [super init];
    if (self) {
        [self startMonitoring];
        [self checkPublicDatabase];
        [self checkUserDatabase];
        _tipsLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 200, 30)];
        _tipsLabel.backgroundColor = [UIColor clearColor];
        _tipsLabel.font = [UIFont systemFontOfSize:17];
        _tipsLabel.textColor = [UIColor blackColor];
        _tipsLabel.textAlignment = NSTextAlignmentCenter;
        _tipsLabel.text = @"未查询到数据";
    }
    return self;
}



#pragma mark 定位
//- (CLLocationCoordinate2D)location
//{
//    if(CLLocationCoordinate2DIsValid(_location))
//    {
//        return _location;
//    }
//    NWInitializeLocationModel *localModel = [NWInitializeLocationModel getUserLocationModel];
//    _location = CLLocationCoordinate2DMake([localModel.latitude doubleValue], [localModel.longitude doubleValue]);
//    return _location;
//}

//- (void)startLocationService
//{
//    self.locationDenied = NO;
//    __weak typeof (self)weakSelf = self;
//    [[AWLocationManager shareLocation] getCity:^(NSString *addressString) {
//        
//        [Singleton shareInstance].currentCityName = [[addressString componentsSeparatedByString:@" "] lastObject];
//        NSLog(@"定位地址 %@",weakSelf.currentCityName);
//        [Singleton shareInstance].currentCity = [NWInitializeCityModel getCityWithName:weakSelf.currentCityName];
//        
//        [Singleton shareInstance].locationDenied = NO;
//    } locationCoordinate:^(CLLocationCoordinate2D locationCorrrdinate) {
//        NSLog(@"经纬度");
//        [Singleton shareInstance].locationDenied = NO;
//        [Singleton shareInstance].location = locationCorrrdinate;
//        NWInitializeLocationModel *localModel = [[NWInitializeLocationModel alloc]init];
//        localModel.latitude = [[NSString alloc]initWithFormat:@"%@",@(locationCorrrdinate.latitude)];
//        localModel.longitude = [[NSString alloc]initWithFormat:@"%@",@(locationCorrrdinate.longitude)];
//        [localModel update];
//        [weakSelf requestToUploadGrid];
//    } error:^(NSError *error) {
//        if (error) {
//            [Singleton shareInstance].locationDenied = YES;
//        }else
//        {
//            
//            [Singleton shareInstance].locationDenied = NO;
//        }
//    }];
//}


//- (void)requestToUploadGrid
//{
//    if ([ Singleton shareInstance].userType == IDENTITY_LAWYER_TYPE&&[ Singleton shareInstance].isLogin&&![Singleton shareInstance].locationDenied)
//    {
//        if (CLLocationCoordinate2DIsValid([Singleton shareInstance].location)) {
//            NWLawHomeRequest *request = [[NWLawHomeRequest alloc]init];
//            [request completion:^(id result, NSString *message, id extension, BOOL succ) {
//                if (succ)
//                {
//                    NSLog(@"位置上传成功");
//                }
//            }];
//            [request requestToUploadGridWithLatitude:[Singleton shareInstance].location.latitude longitudePara:[Singleton shareInstance].location.longitude];
//        }
//        
//    }
//}





#pragma mark SQLite

// 检测SandBox中是否有数据库文件，没有从资源库拷贝到SandBox
- (void)checkUserDatabase
{
    [self checkDatabase:@"KwSystem.sqlite" targetName:@"KwSystem.sqlite" publicDB:NO];
    
}

- (void)checkPublicDatabase
{
    NSString *dbName = @"KwSystem-public.sqlite";
    [self checkDatabase:dbName targetName:dbName publicDB:YES];
}

- (void)checkDatabase:(NSString *)orginName targetName:(NSString *)targetName publicDB:(BOOL)publicDB
{
    BOOL success,needUpdateDbVersion = NO;
    NSString *dbFile = orginName;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:targetName];
    success = [fileManager fileExistsAtPath:writableDBPath];
    if (!success) { // SandBox中没有数据库文件
        // 检测资源库里面是否有数据库文件
        NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:dbFile];
        success = [fileManager fileExistsAtPath:defaultDBPath];
        if (success) {
            // 将数据库文件从资源库拷贝到SandBox
            success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
            if (!success)
            {
                NSLog(@"Failed to create writable database file with message '%@'.", [error localizedDescription]);
            }else
            {
                needUpdateDbVersion = YES;
                //覆盖安装  重置为第一次
                [NSUserDefaults saveObject:@(NO) forKey:kNotFirstUseApp];
                [NSUserDefaults saveObject:@"" forKey:kSysTimeKey];//重置时间参数为空，用于重新拉取初始化数据
            }
        } else {
            NSLog(@"资源库中没有数据库文件：%@", defaultDBPath);
        }
    }
    if (success) {
        FMDatabase *database = [[FMDatabase alloc] initWithPath:writableDBPath];
        if (publicDB)
        {
            _publicDB = database;
        } else {
            _userDB = database;
        }
        if (![database open])
        {
            NSLog(@"open db failed.");
        }
        
        if (needUpdateDbVersion)
        {
            //更新数据库后 把当前dbversion宏定义值 更新到数据库
            BOOL updateSucc = [database executeUpdate:@"UPDATE config set value = ? WHERE key = 'database_version'",@(publicDB ? kPublicDBVersion : kUserDBVersion)];
            if (!updateSucc)
            {
                NSLog(@"update db version failed.");
            }
        }
        
        [self checkDatabaseVersion:database orginName:orginName targetName:targetName publicDB:publicDB];
        NSLog(@"%@", writableDBPath);
    }
    
    // 不备份
    [self addSkipBackupAttributeToItemAtURL:writableDBPath];
}

// 检查数据库文件是否有新版本
- (void)checkDatabaseVersion:(FMDatabase *)database orginName:(NSString *)orginName targetName:(NSString *)targetName publicDB:(BOOL)publicDB
{
    FMResultSet *rs = [database executeQuery:@"SELECT value FROM config WHERE key = 'database_version'"];
    if ([rs next]) {
        NSDictionary *dic = [rs resultDictionary];
        float version = [[dic objectForKey:@"value"] floatValue];
        float newVersion = publicDB ? kPublicDBVersion : kUserDBVersion;
        if (version != newVersion) { // 有新版本，删除原来的数据库文件
            BOOL success;
            NSFileManager *fileManager = [NSFileManager defaultManager];
            NSError *error;
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *documentsDirectory = [paths objectAtIndex:0];
            NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:targetName];
            success = [fileManager fileExistsAtPath:writableDBPath];
            if (success) {
                [fileManager removeItemAtPath:writableDBPath error:&error];
                if (success) {
                    NSLog(@"删除沙盒原数据库成功");//覆盖安装
                    [self checkDatabase:orginName targetName:targetName publicDB:publicDB];
                } else {
                    NSLog(@"%s %d '%@'.", __FUNCTION__, __LINE__, [error localizedDescription]);
                }
            }
        }
    }
}

- (BOOL)addSkipBackupAttributeToItemAtURL:(NSString *)path
{
    NSURL *URL = [NSURL fileURLWithPath:path];
    assert([[NSFileManager defaultManager] fileExistsAtPath:[URL path]]);
    NSError *error = nil;
    BOOL success = [URL setResourceValue:[NSNumber numberWithBool:YES]
                                  forKey:NSURLIsExcludedFromBackupKey
                                   error:&error];
    if (!success) {
        NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error);
    }
    return success;
}

#pragma mark Loading

- (void)startLoading
{
    [self startLoadingInView:((AppDelegate *)[UIApplication sharedApplication].delegate).window];
//    [self startLoadingInView:[UIApplication sharedApplication].keyWindow];
}

- (void)startLoadingInView:(UIView *)view
{
    _loadingCount++;
    
    if (_loadingCount == 1) {
//        _loadingView = [[MBProgressHUD alloc] initWithView:view];
        _loadingView = [MBProgressHUD showHUDAddedTo:view animated:YES];
        _loadingView.color = [UIColor colorWithWhite:0.7 alpha:0.8];
        _loadingView.labelColor = [UIColor blackColor];
//        [_loadingView show:YES];
    } else {
        [_loadingView hide:YES];
        [_loadingView removeFromSuperview];
    }
    [view addSubview:_loadingView];
}

- (void)stopLoading
{
    if (_loadingCount > 0) {
        _loadingCount--;
    }
    
    if (_loadingCount == 0) {
        [_loadingView hide:YES];
        [_loadingView removeFromSuperview];
        _loadingView = nil;
        
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    }
}

- (void)startMonitoring
{
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        switch (status) {
                
            case AFNetworkReachabilityStatusNotReachable:{
                
                NSLog(@"无网络");
                
                break;
                
            }
                
            case AFNetworkReachabilityStatusReachableViaWiFi:{
                
                NSLog(@"WiFi网络");
                
                break;
                
            }
                
            case AFNetworkReachabilityStatusReachableViaWWAN:{
                
                NSLog(@"无线网络");
                
                break;
                
            }
                
            default:
                
                break;
                
        }
        
    }];
    
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];

}

- (NSString *)userId
{
    if (_userId == nil)
    {
        _userId = @"";
    }
    return _userId;
}

- (NSString *)userType
{
    if (_userType == nil)
    {
        _userType = @"";
    }
    return _userType;
}

#pragma app初始化请求 包括数据库处理
- (void)initializeApp:(void(^)(BOOL,NWInitializeVersionModel *,BOOL))completeBlock
{
    __weak typeof (self) weakSelf = self;
#pragma unused(weakSelf)
    NWInitializeRequest  * request = [[NWInitializeRequest alloc]init];
    NSString *time = para_valid([NSUserDefaults retrieveObjectForKey:kSysTimeKey]);

    [request startRequestUpdateApp];
    [request completion:^(id result, NSString *message, id extension, BOOL succ) {
        if (succ)
        {
            NSLog(@"获取app更新成功");
            //            保存服务器时间戳
//            weakSelf.sysTime = result[@"time"];
//            [NSUserDefaults saveObject:para_valid(weakSelf.sysTime) forKey:kSysTimeKey];
//            [weakSelf handleData:result withBlock:completeBlock];
        }else
        {
            completeBlock(NO,nil,time.length == 0);
        }
    }];

    
}

- (void)handleData:(id)result withBlock:(void(^)(BOOL,NWInitializeVersionModel *,BOOL))completeBlock
{
    NSLog(@"开始更新数据");
    //更新数据库版本信息
    NSError *versionError = nil;
    NWInitializeVersionModel *versionModel = [[NWInitializeVersionModel alloc]initWithDictionary:result[@"version"] error:&versionError];
    if (!versionError)
    {
        [versionModel update];
    }
    
    NSLog(@"结束更新数据");
    completeBlock(YES,versionModel,NO);
}

+ (NSString* )getFilePath
{
    return [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
}



@end
